const mongoose = require('./db');
const Schema = mongoose.Schema;

// 校园
const SchoolSchema = new Schema({
    name: String,
    abbreviation: String,
    studentIdRule: {
        pattern: String,  // 学号格式正则表达式
        minLength: Number, // 最小长度
        maxLength: Number, // 最大长度
        description: String // 学号格式说明
    }
});
const Schoolmodel = mongoose.model('school', SchoolSchema, 'school');

// 用户
let userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        min: 3,
        max: 20,
    },
    studentId: {
        type: String,
        required: true,
    },
    schoolId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'school',
        required: true
    },
    password: {
        type: String,
        required: true,
        min: 6
    },
    isAvatarImageSet: {
        type: Boolean,
        default: false,
    },
    avatarImage: {
        type: String,
        default: ""
    },
    qianming: {
        type: String,
        default: '' // 或者空字符串
    },
    isTop: Boolean,
    telp: Number,  // 存放手机号
    following: [{ type: mongoose.Schema.Types.ObjectId, ref: 'user' }],  // 关注的人
    followers: [{ type: mongoose.Schema.Types.ObjectId, ref: 'user' }],  // 粉丝
    // 会员相关字段
    vipLevel: { type: Number, default: 0 }, // 0: 非会员, 1: 月会员, 2: 季会员
    vipExpires: { type: Date, default: null }, // 会员过期时间
    dailyConfessionCount: { type: Number, default: 0 }, // 今日已发表白数
    lastConfessionDate: { type: Date, default: null }, // 最后发帖日期
    voteTickets: { type: Number, default: 0 } // 投票券数量
})
let userModel = mongoose.model('user', userSchema, 'user')

// 消息模型
const MessageSchema = new Schema({
    senderId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user',
        required: true
    },
    receiverId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user',
        required: true
    },
    content: {
        type: String,
        required: true
    },
    messageType: {
        type: String,
        enum: ['text', 'image', 'file'],
        default: 'text'
    },
    isRead: {
        type: Boolean,
        default: false
    },
    timestamp: {
        type: Date,
        default: Date.now
    }
});

const MessageModel = mongoose.model('message', MessageSchema, 'message');

// 聊天会话模型
const ConversationSchema = new Schema({
    participants: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user',
        required: true
    }],
    lastMessage: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'message'
    },
    lastMessageTime: {
        type: Date,
        default: Date.now
    },
    unreadCount: {
        type: Number,
        default: 0
    }
});

const ConversationModel = mongoose.model('conversation', ConversationSchema, 'conversation');

// 群聊模型
const groupSchema = new mongoose.Schema({
    name: {
      type: String,
      required: true,
      min: 2,
      max: 50
    },
    members: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'user'
    }],
    createdBy: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'user',
      required: true
    },
    createdAt: {
      type: Date,
      default: Date.now
    },
    // 记录每个成员最后读取的时间
    memberLastRead: {
      type: Map,
      of: Date,
      default: {}
    },
    // 记录每个成员的未读消息数
    memberUnreadCount: {
      type: Map,
      of: Number,
      default: {}
    },
    announcement: {
      content: { type: String, default: "" },
      publisher: { type: String, default: "" },
      avatar: { type: String, default: "" },
      time: { type: Date }
    },
  });
  const groupModel = mongoose.model('group', groupSchema, 'group');
  
  // 群聊消息模型
  const groupMessageSchema = new mongoose.Schema({
    groupId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'group',
      required: true
    },
    from: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'user',
      required: true
    },
    content: {
      type: String,
      required: true
    },
    messageType: {
      type: String,
      enum: ['text', 'emoji', 'image', 'voice', 'video', 'system'],
      required: true
    },
    audioData: {
      type: String, // Base64编码的音频数据
      required: false
    },
    duration: {
      type: Number, // 音频时长（秒）
      required: false
    },
    videoData: {
      type: String, // Base64编码的视频数据
      required: false
    },
    quote: {
      sender: String,
      content: String
    },
    time: {
      type: Date,
      default: Date.now
    }
  });
  const groupMessageModel = mongoose.model('groupMessage', groupMessageSchema, 'groupMessage');



// 校园卡数据模型
const CampusCardSchema = new Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user',
        required: true,
        unique: true // 每个用户只能有一张校园卡
    },
    cardNumber: {
        type: String,
        required: true,
        unique: true // 卡号唯一
    },
    balance: {
        type: Number,
        default: 0,
        min: 0 // 余额不能为负数
    },
    isActive: {
        type: Boolean,
        default: true // 卡片是否激活
    },
    isLost: {
        type: Boolean,
        default: false // 是否挂失
    },
    bindTime: {
        type: Date,
        default: Date.now // 绑定时间
    },
    lastSyncTime: {
        type: Date,
        default: Date.now // 最后同步时间
    }
});

const CampusCardModel = mongoose.model('campusCard', CampusCardSchema, 'campusCard');

// 饭卡数据模型（云缴费系统）
const MealCardSchema = new Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user',
        required: true,
        unique: true // 每个用户只能有一张饭卡
    },
    cardNumber: {
        type: String,
        required: true,
        unique: true // 卡号唯一
    },
    balance: {
        type: Number,
        default: 0,
        min: 0 // 余额不能为负数
    },
    isActive: {
        type: Boolean,
        default: true // 卡片是否激活
    },
    bindTime: {
        type: Date,
        default: Date.now // 绑定时间
    },
    lastSyncTime: {
        type: Date,
        default: Date.now // 最后同步时间
    }
});

const MealCardModel = mongoose.model('mealCard', MealCardSchema, 'mealCard');

// 交易记录数据模型
const TransactionSchema = new Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user',
        required: true
    },
    cardType: {
        type: String,
        enum: ['campus', 'meal'], // 校园卡或饭卡
        required: true
    },
    type: {
        type: String,
        enum: ['recharge', 'consume', 'sync'], // 充值、消费、同步
        required: true
    },
    amount: {
        type: Number,
        required: true
    },
    balanceBefore: {
        type: Number,
        required: true
    },
    balanceAfter: {
        type: Number,
        required: true
    },
    location: {
        type: String,
        default: ''
    },
    description: {
        type: String,
        default: ''
    },
    transactionTime: {
        type: Date,
        default: Date.now
    }
});

const TransactionModel = mongoose.model('transaction', TransactionSchema, 'transaction');

module.exports = {
    Schoolmodel,
    userModel,
    MessageModel,
    groupModel,
    groupMessageModel,
    ConversationModel,
    CampusCardModel,
    MealCardModel,
    TransactionModel
};

